package com.infodeli.component.Interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.infodeli.common.exception.ExceptionEnum;
import com.infodeli.common.utils.JWTUtils;
import com.infodeli.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JWTInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if(requestTokenPass(request)){
            return true;
        }

        // 将 JWT 放在 请求头
        String token = request.getHeader("token");
        if("Upgrade".equals(request.getHeader("Connection"))){
            token = request.getHeader("Sec-WebSocket-Protocol");
            System.out.println(request.getRequestURI()+"建立ws连接，token:"+token);
            //response.setHeader("Sec-WebSocket-Protocol",token);
        }

        ExceptionEnum error = null;
        if(token == null || token.equals("")){
            error = ExceptionEnum.USER_TOKEN_NOT_EXIST;
        }
        try{
            JWTUtils.verify(token);
            log.info("请求通过["+request.getRequestURI()+"]");
            return true;
        }catch(SignatureVerificationException e){
            error = ExceptionEnum.USER_TOKEN_SIGNATURE;
        }catch(AlgorithmMismatchException e){
            error = ExceptionEnum.USER_TOKEN_ALGORITHM;
        }catch(TokenExpiredException e){
            error = ExceptionEnum.USER_TOKEN_EXPIRE;
        }catch(Exception e){
            error = ExceptionEnum.USER_TOKEN_ERROR;
        }
        log.info("请求拦截["+request.getRequestURI()+"]");
        R r = R.error(error.getCode(), error.getMsg());
        String json = new ObjectMapper().writeValueAsString(r);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

    public boolean requestTokenPass(HttpServletRequest request){
        String tokenPass = request.getHeader("token-pass");
        if(tokenPass != null && "yes".equals(tokenPass)){
            return true;
        }
        return false;
    }
}
